<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>

<!-- 添加和条件查询-->
        <div class="container">
            <div class="handle-box">
                <el-button
                    type="primary"
                    icon="el-icon-add"
                    class="handle-del mr10"
                    @click="handleEdit('add')"
                >添加</el-button>
                <el-button
                    type="primary"
                    icon="el-icon-delete"
                    class="handle-del mr10"
                    @click="delAllSelection"
                >批量删除</el-button>
                <el-select v-model="query.userType" placeholder="职位" class="handle-select mr10">
                    <el-option key="1" label="律师" value="1"></el-option>
                    <el-option key="2" label="行政主管" value="2"></el-option>
                    <el-option key="3" label="律所主任" value="3"></el-option>
                </el-select>

                <el-input v-model="query.userName" placeholder="用户名" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>

<!--主页面展示的表格-->
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="userId" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="userName" label="用户名"></el-table-column>
                <el-table-column prop="phoneNumber" label="电话"></el-table-column>
                <el-table-column prop="roleName" label="角色"></el-table-column>

                <el-table-column label="用户状态">
                    <template slot-scope="scope">
                        <el-switch
                            v-model="scope.row.isActive"
                            active-color="#13ce66"
                            inactive-color="#909399" @change='chanActive(scope.row)'>
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="用户操作" width="240" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit('edit', scope.row)"
                        >编辑</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-refresh"
                            @click="resetPsd(scope.$index, scope.row)"
                        >重置密码</el-button>
                        <el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>
                    </template>
                </el-table-column>

            </el-table>

<!--分页-->
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!--编辑弹出框 -->
        <el-dialog :title="title" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-form-item label="用户名" prop='userName'>
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop='phoneNumber'>
                    <el-input v-model="form.phoneNumber"></el-input>
                </el-form-item>
                <el-form-item label="角色" prop='userType'>
                    <el-select v-model="form.userType" placeholder="请选择">
                        <el-option
                            v-for="role in roles"
                            :key="role.roleId"
                            :label="role.roleName"
                            :value="role.roleId"
                        ></el-option>
                    </el-select>

                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { getUsersByCondition,changeUserActive,editUser,addUser,delUser,reSetPassword} from "../../api/user";
import {getRoles} from "../../api/role"
export default {
    name: 'UserQuery',
    data() {
        return {
            /*条件查询*/
            query: {
                userName: '',
                userType:"",
                page: 1,
                pageSize: 10
            },


            tableData: [],//页面 查询的表格数据
            pageTotal: 0,//总条数


            multipleSelection: [],//复选框选中的数据
            delList: [], //批量删除的ids



            //----编辑
            title:"添加",
            //编辑中角色下拉框
            roles:[],
            editVisible: false, //对话框显示不显示
            form: {},//添加/编辑提交表单后数据放在form里，添加或修改的表单数据
            rules:{
                userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                phoneNumber:[ { required: true, message: '请输入手机号', trigger: 'blur' },
                    {
                        pattern: /^1[3-9]\d{9}$/,
                        message: '请输入有效的手机号码',
                        trigger: 'blur'
                    }],
                roleId:[{ required: true, message: '请选择角色', trigger: 'change'}]
            },


            idx: -1,//弹框时告诉修改/删除第几行
            id: -1
        };
    },
    created() {
        this.getData();
    },
    methods: {
        //重置密码
        resetPsd(index, row) {
            // 二次确认删除
            this.$confirm('确定要重置密码为123456吗', '提示',{
                type:'warning'
            })
                .then(()=>{
                        // alert(row.userId)
                    reSetPassword(row.userId).then(res=>{
                        if(res.code=200) {
                            this.$message.success("密码已重置为123456")
                        }
                        else{
                            this.$message.error("密码重置失败")
                        }
                    })
                    }

                )
                .catch(() => {});
        },
        //改变启用状态
        chanActive(val){
          changeUserActive(val).then(res=>{
                if(res.code==200) {
                    if(val.isActive==true){
                        this.$message.success("用户已启用")
                    }else{
                        this.$message.info("用户已禁用")
                    }
                }
                else{
                    this.$message.error("启用/禁用失败,稍后再试")
                }
          })
        },


        // 一加载页面就获取 user数据
        getData() {
            getUsersByCondition(this.query).then(res=>{
                if(res.code == 200) {
                    // console.log(res);
                        this.tableData = res.data.list;
                        // console.log(this.tableData)
                        this.pageTotal = res.pageTotal || 50;
                    }
                    else {
                        this.$message.error(res.msg);
                }
            })
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(()=>{
                        // alert(row.userId)
                        delUser([row.phoneNumber]).then((res) => {
                            console.log(res);
                            if(res.code==200){
                                this.$message.success('删除成功');
                                this.getData();
                            }
                            else{
                                this.$message.error('删除失败');
                            }
                        })
                    }
                )
                .catch(() => {});
        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllSelection() {
            for(let i = 0;i < this.multipleSelection.length;i++) {
                this.delList.push(this.multipleSelection[i].userId);
            }
            console.log(this.delList)
            // const length = this.multipleSelection.length;
            delUser(this.delList).then(res=>{
                console.log(res);
                if(res.code==200) {
                    this.$message.success('批量删除成功');
                    this.getData();
                }else{
                    this.$message.error('批量删除失败');
                }
            })
        },
        // 编辑操作
        handleEdit(ope, row) {
            getRoles().then(res=>{
                if(res.code == 200) {
                    this.roles = res.data;
                }else {
                    this.$message.error(res.msg)
                }
            })
            if(ope == 'edit') {
                this.title = "编辑";
                this.form = { ...row };
            }else{
                this.title = "添加"
            }
            this.editVisible = true;
        },
        // 保存编辑
        saveEdit() {
            this.$refs.form.validate(valid => {
                if(valid) {
                    if(this.title == '编辑') {
                        console.log("form1",this.form);
                        editUser(this.form).then(res=>{
                            if(res.code==200) {
                                this.$message.success("修改成功")
                                this.editVisible = false;
                                this.getData();
                            }else {
                                this.$message.error("修改失败")
                            }

                        })
                    }else{//添加
                        addUser(this.form).then(res=>{
                            if(res.code==200) {
                                this.$message.success("添加成功")
                                this.editVisible = false;
                                this.getData();
                            }else {
                                this.$message.error("添加失败")
                            }
                        })
                    }
                }else{
                    this.$message.error('请输入正确的信息')
                    return false;
                }
            })
            // this.editVisible = false;
            // this.$message.success(`修改第 ${this.idx + 1} 行成功`);
            // this.$set(this.tableData, this.idx, this.form);
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'page', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
